package de.fhb.easymealtime.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import de.fhb.easymealtime.manager.IKitchen;
import de.fhb.easymealtime.manager.Kitchen;
import de.fhb.easymealtime.repository.rezeptVO;
import de.fhb.easymealtime.repository.zutatVO;

/**
 * Servlet implementation class add
 */
@WebServlet("/add")
public class add extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
	IKitchen kitchen = new Kitchen();
	boolean falscheEingabe = false;
    public add() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String nextJsp = "add.jsp";
		
		
		if(request.getParameter("Submit") != null)
		{
			Enumeration<String> parameter = request.getParameterNames();
			while(parameter.hasMoreElements())
				if(request.getParameter(parameter.nextElement() ).equals(""))
				{
					falscheEingabe = true;

					
				}
			
			if(!falscheEingabe)
			{
				nextJsp = "add.jsp";
				List<zutatVO> zutaten = new ArrayList<zutatVO>();
				rezeptVO rezept = new rezeptVO();
				rezept.setName(request.getParameter("RezeptName"));
				rezept.setRezept(request.getParameter("Rezept"));
				
				int counter = Integer.valueOf(request.getParameter("zutaten"));
				
				
				
				
						
				
				for(int i=0;i<counter;i++){
					zutaten.add(new zutatVO(request.getParameterValues("Zname")[i],
											Integer.valueOf(request.getParameterValues("Zpreis")[i]),
											Integer.valueOf(request.getParameterValues("Zmenge")[i]),
											Integer.valueOf(request.getParameterValues("Zkcal")[i])));
				}
				rezept.setZutaten(zutaten);
				
				System.out.println(rezept);
				
				kitchen.InsertRezept(rezept);
			
			}
			else
			{
				nextJsp = "Error.jsp";
			}
		
		}
		RequestDispatcher req = request.getRequestDispatcher(nextJsp);
		req.forward(request, response);
		

	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

}
